package com.example.transactional.controller;

import com.example.transactional.common.constant.CacheConstants;
import com.example.transactional.common.redis.RedisCache;
import com.example.transactional.entity.User;
import com.example.transactional.service.UserService;
import com.example.transactional.util.StringUtils;
import com.example.transactional.util.cache.UserCacheUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/user")
@Api(value = "用户信息", tags = "用户信息")
public class UserController {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    @ApiOperation(value = "分页获取用户信息", notes = "分页获取用户信息")
    public List<User> getUserByPage() {
        List users = UserCacheUtils.getUsersCache("*");
        if (StringUtils.isNotNull(users)) {
            return users;
        }
        users = userService.selectUserList();
        UserCacheUtils.setUserListCache("*", users);
        return users;
    }

    @GetMapping("/save")
    @ApiOperation(value = "保存用户信息", notes = "保存用户信息")
    public boolean saveUser() {
        User user = new User();
        user.setName("haha");
        user.setAge(25);
        try {
            boolean flag = userService.saveUser(user) == 1;
            if (flag) {
                UserCacheUtils.setUserCache(user.getName(), user);
                UserCacheUtils.clearDictCache();
            }
            return flag;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}
